package org.minapp.idiom.service.impl;

import org.minapp.idiom.base.service.BaseService;
import org.minapp.idiom.base.service.BaseServiceImpl;
import org.minapp.idiom.module.FileUploadInfo;
import org.minapp.idiom.service.FileUploadService;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.lang.util.Disks;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@IocBean(args = {"refer:dao"})
public class FileUploadServiceImpl extends BaseServiceImpl<FileUploadInfo> implements FileUploadService {
    private String filePath;


    public FileUploadServiceImpl(Dao dao) {
        super(dao);
        Properties properties = new Properties();
        InputStream in = FileUploadServiceImpl.class.getResourceAsStream("/application.properties");
        try{
            properties.load(in);
            filePath = properties.getProperty("fd.filepath");
        }catch (Exception e){

        }finally {
            try {
                in.close();
            }catch (IOException e){

            }
        }


    }

    @Override
    public List<FileUploadInfo> upload(List<String> filePaths) {
        List<FileUploadInfo> uploadInfoList = new ArrayList<>();
        for (String filePath:filePaths){
            File file = new File(filePath);
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setExName(Files.getSuffixName(file));
            String serverPath = this.getPath();
            serverPath+= R.UU16()+"."+fileUploadInfo.getExName();
            fileUploadInfo.setServerPath(serverPath);
            uploadInfoList.add(fileUploadInfo);
            Files.copy(file,new File(serverPath));
        }
        this.insert(uploadInfoList);


        return uploadInfoList;
    }

    private String getPath(){
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String finderName = df.format(new Date());
        String path = this.filePath+File.separator+finderName+File.separator;
       // File finderFile = new File(path);
        //System.out.println("--------------------------------"+path);

        File finderFile = new File(Disks.normalize(path));
        synchronized (finderFile){
            Files.createDirIfNoExists(finderFile);
        }
        return finderFile.getAbsolutePath()+File.separator;
    }

}
